import React, {useEffect, useState} from "react";
import {Button, Input, Modal, Space} from "antd";
import UploadImg from "@/pages/ThemeConfig/UploadImg";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import actions from "@/config/actions";
import {apiUpdateSiteConfig} from "@/common/apis/setting-api";

interface ConfigItemProps {
  name: string;
  type?: "text" | "image"; //区分组件类型
  title: string; // 标题
  value?: string;
  onChange?: (value: any) => void;
  maxLength?: number; // 输入框长度
  crop?: boolean; // 是否需要剪切
  accept?: string; // 图片上传接受的文件类型
}

const ConfigItem: React.FC<ConfigItemProps> = (props) => {
  const {
    name,
    title,
    type = "text",
    onChange,
    maxLength,
    value,
    crop = false,
    accept,
  } = props;

  // console.log(name, value)

  const [text, setText] = useState<string>();
  const [btnLoading, setBtnLoading] = useState(false)

  useEffect(() => {
    setText(value);
  }, [value]);

  const saveTitle = () => {
    setBtnLoading(true)
    apiUpdateSiteConfig({key: name, value: value, tenantId: 1}).then(res => {
      if (res.code === 0) {
        actions.sendMessage2MainApp(res.data)
      }
    }).finally(() => setBtnLoading(false))

    /*Modal.confirm({
      title: '确定恢复默认值吗？',
      icon: <ExclamationCircleOutlined/>,
      onOk: () => {
        console.log(name)
        actions.sendMessage2MainApp({
          siteConfig: {
            logo: 'http://localhost:8080/Image/11623753869_.pic.jpg'
          }
        })
      }
    })*/
  };

  const inputChange = (e: any) => {
    console.log(e.target.value)
    setText(e.target.value);
    if (onChange) {
      onChange(e.target.value);
    }
  };

  return (
    <div style={{marginBottom: "10px"}}>
      <Space align={type === "text" ? "center" : "start"}>
        <div style={{width: "120px"}}>{title} :</div>
        {type === "text" ? (
          <Space>
            <Input
              size="small"
              value={value}
              onChange={inputChange}
              maxLength={maxLength}
              style={{width: "300px"}}
              disabled={btnLoading}
            />
            <Button size="small" type="primary" ghost onClick={saveTitle}>保存</Button>
          </Space>
        ) : (
          <UploadImg
            onChange={onChange}
            value={value}
            crop={crop}
            accept={accept}
          />
        )}
      </Space>
    </div>
  );
}

export default ConfigItem
